package com.shxc.smarttrade.utils.analysis;

import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;

public class JsonAnalysisUtils {

    /**
     * 解析json
     *
     * @param result 回调得到的json
     */
    public static JsonAnalysisModel jsonAnalysis(String result) {
        Gson gson = new Gson();
        JsonAnalysisModel model = new JsonAnalysisModel();
        try {
            JSONObject resultJson = new JSONObject(result);
            String resultCode = resultJson.getString("err_code");
            if (resultCode.equals("0")) {
                model.setSuccess(true);
            } else {
                model.setSuccess(false);
                model.setMsg(resultJson.getString("err_msg"));
            }


        } catch (JSONException e) {
            e.printStackTrace();
        }

        return model;
    }


    /**
     * 解析json
     *
     * @param result 回调得到的json
     * @param type   解析用类型
     */
    public static JsonAnalysisModel jsonAnalysis(String result, Type type) {
        Gson gson = new Gson();
        JsonAnalysisModel model = new JsonAnalysisModel();
        try {
            JSONObject resultJson = new JSONObject(result);
            String resultCode = resultJson.getString("err_code");
            if (resultCode.equals("0")) {
                model.setSuccess(true);
                Object obj = gson.fromJson(result, type);
                model.setData(obj);
            } else {
                model.setSuccess(false);
                model.setMsg(resultJson.getString("err_msg"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return model;
    }
}
